<template>
  <el-space>
    <el-input-number v-model="begin" :placeholder="startPlaceholder" v-bind="controlSet">
      <template #suffix>
        <slot name="suffix"></slot>
      </template>
      <template #prefix>
        <slot name="prefix"></slot>
      </template>
    </el-input-number>
    <span>{{ rangeSeparator }}</span>
    <el-input-number v-model="end" :placeholder="endPlaceholder" v-bind="controlSet">
      <template #suffix>
        <slot name="suffix"></slot>
      </template>
      <template #prefix>
        <slot name="prefix"></slot>
      </template>
    </el-input-number>
  </el-space>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes'
import { ref, unref, watch, onMounted } from 'vue'

const emit = defineEmits(['update:modelValue'])

const props = defineProps({
  modelValue: propTypes.arrayOf(propTypes.number),
  startPlaceholder: propTypes.string.def('起始值'),
  endPlaceholder: propTypes.string.def('起始值'),
  rangeSeparator: propTypes.string.def('至'),
  min: propTypes.number,
  max: propTypes.number,
  step: propTypes.number.def(1),
  precision: propTypes.number,
  size: propTypes.oneOf(['large', 'default', 'small']).def('default'),
  controls: propTypes.bool.def(true),
  controlsPosition: propTypes.oneOf(['', 'right']).def('right')
})
const begin = ref<number | null | undefined>(null)
const end = ref<number | null | undefined>(null)
const controlSet = ref<object>({
  min: null,
  max: null,
  step: null,
  precision: null,
  size: null,
  controls: true,
  controlsPosition: null
})
onMounted(() => {
  controlSet.value = {
    min: props.min,
    max: props.max,
    step: props.step,
    precision: props.precision,
    size: props.size,
    controls: props.controls,
    controlsPosition: props.controlsPosition
  }
  reset(props.modelValue)
})
const reset = (val: (number | null | undefined)[] | null | undefined) => {
  if (val == null || val == undefined) {
    begin.value = null
    end.value = null
  } else if (val.length == 1) {
    begin.value = val[0]
    end.value = null
  } else {
    begin.value = val[0]
    end.value = val[1]
  }
}
watch(
  () => unref(props).modelValue,
  (val) => {
    reset(val)
  },
  {
    immediate: false
  }
)
watch(
  () => unref(begin),
  (val: number | null | undefined) => {
    if (val && end.value) {
      emit('update:modelValue', [val, end.value])
    }
  },
  {
    immediate: false,
    deep: true
  }
)
watch(
  () => unref(end),
  (val: number | null | undefined) => {
    if (val && begin.value) {
      emit('update:modelValue', [begin.value, val])
    }
  },
  {
    immediate: false,
    deep: true
  }
)
</script>
